// HTTP/3 masquerade - pretend to be a normal HTTPS server

use axum::{
    Router,
    response::{IntoResponse, Response},
    http::StatusCode,
};
use std::net::SocketAddr;
use tracing::info;

#[derive(Debug, Clone)]
pub enum MasqueradeMode {
    File(String),      // Serve a file
    Proxy(String),     // Proxy to another server
    String(String),    // Return a string
    Status(u16),       // Return a status code
}

pub struct MasqueradeServer {
    mode: MasqueradeMode,
    listen_addr: SocketAddr,
}

impl MasqueradeServer {
    pub fn new(mode: MasqueradeMode, listen_addr: SocketAddr) -> Self {
        Self { mode, listen_addr }
    }

    pub async fn run(&self) -> anyhow::Result<()> {
        info!("Masquerade server listening on {}", self.listen_addr);
        
        let app = Router::new()
            .fallback(|| async { self.handle_request().await });
        
        let listener = tokio::net::TcpListener::bind(self.listen_addr).await?;
        axum::serve(listener, app).await?;
        
        Ok(())
    }

    async fn handle_request(&self) -> Response {
        match &self.mode {
            MasqueradeMode::String(s) => {
                (StatusCode::OK, s.clone()).into_response()
            }
            MasqueradeMode::Status(code) => {
                StatusCode::from_u16(*code)
                    .unwrap_or(StatusCode::OK)
                    .into_response()
            }
            MasqueradeMode::File(path) => {
                match tokio::fs::read_to_string(path).await {
                    Ok(content) => (StatusCode::OK, content).into_response(),
                    Err(_) => StatusCode::NOT_FOUND.into_response(),
                }
            }
            MasqueradeMode::Proxy(url) => {
                // TODO: Implement proxy mode
                (StatusCode::OK, format!("Proxy to {}", url)).into_response()
            }
        }
    }
}
